//
//  SCHomeViewController.swift
//  weibo
//
//  Created by 阿城 on 15/12/5.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit
import SVProgressHUD

private let showBarHeight: CGFloat = 40

class SCHomeViewController: SCBasicTableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
//        printLog(tabBarItem)
//        printLog(self.tabBarController?.tabBarItem)
//        printLog(navigationItem)
//        printLog(navigationController?.navigationItem)
//        printLog(navigationController?.navigationBar)
        
        //设置UI
        setupTableView()
        

    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if visitorView != nil{
            return
        }
        
        showCount.frame = CGRect(x: 0, y: tableView.contentInset.top - showBarHeight, width: kScreenWidth, height: showBarHeight)
        
    }
    
    @objc private func barButtonClick(){
        printLog("barButtonClick")
        let vc = SCTestViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    let statusList = SCStatusesListViewModel()
    
    private lazy var activity: UIActivityIndicatorView = {
        let act = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        act.startAnimating()
        act.color = UIColor.orangeColor()
        return act
    }()
    private lazy var showCount: SCShowLoadingCountView = SCShowLoadingCountView()
}


extension SCHomeViewController{
    
    
    private func setupTableView(){
        
        if visitorView != nil {
            
            visitorView?.setDetail(nil, text: nil)
            return
        }
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch", target: self, action: "barButtonClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", target: self, action: "barButtonClick")
        
        //获取数据
        statusList.loadData { (isSeccess,num) -> () in
            if !isSeccess {
                printLog("加载错误")
                SVProgressHUD.showInfoWithStatus("加载错误", maskType: SVProgressHUDMaskType.Black)
            }
            self.tableView.reloadData()
            self.showCount.count = num
        }
        
        //配置tableview
        tableView.registerClass(SCHomeTableViewCell.self, forCellReuseIdentifier: "cell")
//        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        tableView.separatorStyle = .None
        tableView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        
        //添加刷新控件
        let refresh: SCRefresh = SCRefresh()
        tableView.addSubview(refresh)
        refresh.addTarget(self, action: "refreshData:", forControlEvents: UIControlEvents.ValueChanged)
        
        //添加展示空间
        navigationController?.view.insertSubview(showCount, belowSubview: (navigationController?.navigationBar)!)
    }
    
    // MARK: - 下拉刷新
    @objc private func refreshData(refresh: SCRefresh){
        
        printLog("加载")
        statusList.loadData { (isSeccess,num) -> () in
            if !isSeccess {
                printLog("加载错误")
                SVProgressHUD.showInfoWithStatus("加载错误", maskType: SVProgressHUDMaskType.Black)
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                
                self.tableView.reloadData()
                refresh.endLoading()
                self.showCount.count = num
            })
        }
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusList.statusListArr?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! SCHomeTableViewCell

        cell.selectionStyle = .None
        cell.statusViewModel = statusList.statusListArr![indexPath.row]
        
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        let height = tableView.rectForRowAtIndexPath(indexPath).height
        printLog("\(indexPath.row)----\(height)")
        
        if indexPath.row == statusList.statusListArr!.count - 1{
            tableView.tableFooterView = activity
            statusList.loadData(true, backClosure: { (isSeccess,num) -> () in
                if !isSeccess {
                    printLog("加载错误")
                    SVProgressHUD.showInfoWithStatus("加载错误", maskType: SVProgressHUDMaskType.Black)
                    return
                }
                
                //模拟延时
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    
                    tableView.reloadData()
                    tableView.tableFooterView = nil
                    
                })
                
            })
        }
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        printLog("heightForRowAtIndexPath")
        return UITableViewAutomaticDimension
    }
    
    
}


